package com.cke.yang.storage.domain.repository.impl;

import com.cke.yang.common.infra.enums.SaveActionEnum;
import com.cke.yang.storage.domain.entity.StgSource;
import com.cke.yang.storage.domain.repository.StgSourceRepository;
import com.cke.yang.storage.infra.mapper.StgSourceMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: luozhaojian
 * @description:
 * @date: 2025/10/7 11:04
 */
@Repository
public class StgSourceRepositoryImpl implements StgSourceRepository {

    @Autowired
    private StgSourceMapper stgSourceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StgSource saveByAction(SaveActionEnum action, StgSource stgSource) {
        switch (action) {
            case INSERT:
                return insert(stgSource);
            case UPDATE:
                return update(stgSource);
            case DELETE:
                return delete(stgSource);
            default:
                return null;
        }
    }

    @Override
    public StgSource insert(StgSource stgSource) {
        if (stgSource.getIsDefault() == 1) {
            // 找到默认的数据源并更新为非默认
            this.selectDefaultAndUpdate();
        }
        stgSourceMapper.insert(stgSource);
        return stgSource;
    }

    @Override
    public StgSource update(StgSource stgSource) {
        stgSourceMapper.updateById(stgSource);
        return stgSource;
    }

    @Override
    public StgSource delete(StgSource stgSource) {
        stgSourceMapper.deleteById(stgSource);
        return stgSource;
    }

    @Override
    public void selectDefaultAndUpdate() {
        QueryWrapper<StgSource> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StgSource::getIsDefault, 1);
        StgSource stgSource = stgSourceMapper.selectOne(queryWrapper);
        if (stgSource == null) {
            return;
        }
        UpdateWrapper<StgSource> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(StgSource::getIsDefault, 0)
                        .eq(StgSource::getSourceId, stgSource.getSourceId());
        this.updateByWrapper(updateWrapper);
    }

    @Override
    public void updateByWrapper(UpdateWrapper<StgSource> updateWrapper) {
        stgSourceMapper.update(null, updateWrapper);
    }

    @Override
    public List<StgSource> findBySourceOwner(Long sourceOwner) {
        QueryWrapper<StgSource> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StgSource::getSourceOwner, sourceOwner);
        return stgSourceMapper.selectList(queryWrapper);
    }
}
